package com.wust.supermarket.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wust.supermarket.domain.Provider;
import com.wust.supermarket.domain.Response;
import com.wust.supermarket.service.ProviderService;

@Controller
public class ProviderController {
	@Autowired
private ProviderService providerSerivce;

	@GetMapping("/provider/list")
	public String ListProvider(Model model) {
		List<Provider> providers=providerSerivce.listAllProviders();
		model.addAttribute("providers",providers);
		List<Provider> providers1=providerSerivce.listProviderOffline();
		model.addAttribute("providers1",providers1);
		return "provider/ListProvider";
	} 
	
	@RequestMapping(value = "/provider/addProvider",method = RequestMethod.GET)
    public String p() {
        return "provider/addProvider";
    }
	@ResponseBody
	@GetMapping("/provider/getbyid/{id}")
	public Provider getProviderById(@PathVariable("id") int providerId) {
		Provider provider= providerSerivce.getProviderById(providerId);
		if(provider==null)
			return null;
		else 
			return provider;
	}

	@ResponseBody
    @PostMapping("/provider/insert")
    public Response insertProvider(@RequestBody Provider provider) {
		System.out.println(provider);
    	if(providerSerivce.insertProvider(provider)>0)
    		return new Response<>(1, "插入成功", null);
        else
            return new Response<>(-1, "插入失败", null);
    }

	@ResponseBody
    @PostMapping("/provider/update")
    public Response updateProvider(@RequestBody Provider provider) {
    	if(providerSerivce.updateProvider(provider)>0)
                return new Response<>(1, "修改成功", null);
            else
                return new Response<>(-1, "修改失败", null);
    }

	@ResponseBody
    @PostMapping("/provider/delete/{id}")
    public Response deleteProvider(@PathVariable("id") int providerId) {
    	if(providerSerivce.deleteProvider(providerId)>0)
    		return new Response<>(1, "删除成功", null);
        else
            return new Response<>(-1, "删除失败", null);
    }

}
